package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 定时任务类
 */
@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrderMapper orderMapper;
    /**
     * 每分钟查询订单状态，处理超时未支付订单（15分钟）
     */
    @Scheduled(cron = "0 * * * * ? ") //每分钟触发一次
    public void processUnPaidOrder(){
        log.info("处理超时未支付订单：{}", LocalDateTime.now());
        List<Orders> orders=orderMapper.getOrdersByStatusAndLatestTime(Orders.PENDING_PAYMENT,LocalDateTime.now().plusMinutes(-15));
        if(orders!=null&&!orders.isEmpty()){
            orders.forEach(order->{
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason(MessageConstant.UNPAID_ORDER_TIMEOUT);
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }
    }

    /**
     * 派送中的订单每日凌晨1点进行清洗
     */
    @Scheduled(cron = "0 0 1 * * ?") //每日凌晨一点触发
    public void processInDeliveryOrder(){
        log.info("处理派送中订单：{}",LocalDateTime.now());
        List<Orders> orders=orderMapper.getOrdersByStatusAndLatestTime(Orders.DELIVERY_IN_PROGRESS,LocalDateTime.now().plusMinutes(-60));
        if(orders!=null&&!orders.isEmpty()){
            orders.forEach(order->{
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }
    }
}
